﻿<template>
	<div class="card-fill layout-padding" v-loading="loading" element-loading-text="Loading...">
		<WtmSearcher v-if="searchBar" v-model="searchData" @search="getTableData" :showToggleAdvanced="true" :defaultExpandAdvanced="false">
			<template #primary="{ showAdvanced }">
				<el-row :gutter="15">
					<!-- 常用搜索条件 -->
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Name_FormItem" prop="Name">
							<template #label>
								<WtmLabelTooltip label="姓名" tooltip="员工姓名" />
							</template>
							<el-input v-model="searchData.Name" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="StaffNo_FormItem" prop="StaffNo">
							<template #label>
								<WtmLabelTooltip label="工号" tooltip="员工工号" />
							</template>
							<el-input v-model="searchData.StaffNo" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="State_FormItem" prop="State">
							<template #label>
								<WtmLabelTooltip label="人员状态" tooltip="人员状态" />
							</template>
							<el-select v-model="searchData.State" clearable>
								<el-option key="在职" value="在职" label="在职"></el-option>
								<el-option key="试用期" value="试用期" label="试用期"></el-option>
								<el-option key="退休" value="退休" label="退休"></el-option>
								<el-option key="离职" value="离职" label="离职"></el-option>
								<el-option key="辞退" value="辞退" label="辞退"></el-option>
								<el-option key="待入职" value="待入职" label="待入职"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<WtmOrgSelector v-model="searchData.OrgId" :clearable="true" :filterable="true" placeholder="请选择公司" label="公司" tooltip="公司" />
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Phone_FormItem" prop="Phone">
							<template #label>
								<WtmLabelTooltip label="手机号" tooltip="手机号" />
							</template>
							<el-input v-model="searchData.Phone" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
						<el-form-item ref="Gender_FormItem" prop="Gender">
							<template #label>
								<WtmLabelTooltip label="性别" tooltip="性别" />
							</template>
							<el-select v-model="searchData.Gender" clearable>
								<el-option key="男" value="男" label="男"></el-option>
								<el-option key="女" value="女" label="女"></el-option>
								<el-option key="其他" value="其他" label="其他"></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<!-- 可展开的详细搜索条件 -->
					<template v-if="showAdvanced">
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="BirthDate_FormItem" prop="BirthDate">
								<template #label>
									<WtmLabelTooltip label="出生日期" tooltip="出生日期" />
								</template>
								<el-date-picker type="daterange" v-model="searchData.BirthDate" clearable></el-date-picker>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="Ethnicity_FormItem" prop="Ethnicity">
								<template #label>
									<WtmLabelTooltip label="民族" tooltip="民族" />
								</template>
								<el-select v-model="searchData.Ethnicity" clearable>
									<el-option key="汉族" value="汉族" label="汉族"></el-option>
									<el-option key="回族" value="回族" label="回族"></el-option>
									<el-option key="满族" value="满族" label="满族"></el-option>
									<el-option key="蒙古族" value="蒙古族" label="蒙古族"></el-option>
									<el-option key="壮族" value="壮族" label="壮族"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="AgeRange_FormItem" prop="AgeRange">
								<template #label>
									<WtmLabelTooltip label="年龄范围" tooltip="年龄范围" />
								</template>
								<div class="range-input-container">
									<el-input-number
										v-model="searchData.AgeStart"
										:min="0"
										:max="150"
										controls-position="right"
										:controls="false"
										placeholder="起始"
										clearable
										class="range-input-start"
									></el-input-number>
									<span class="range-separator">至</span>
									<el-input-number
										v-model="searchData.AgeEnd"
										:min="0"
										:max="150"
										controls-position="right"
										:controls="false"
										placeholder="结束"
										clearable
										class="range-input-end"
									></el-input-number>
								</div>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="HighestEducation_FormItem" prop="HighestEducation">
								<template #label>
									<WtmLabelTooltip label="最高学历" tooltip="最高学历" />
								</template>
								<el-select v-model="searchData.HighestEducation" clearable>
									<el-option key="小学" value="小学" label="小学"></el-option>
									<el-option key="初中" value="初中" label="初中"></el-option>
									<el-option key="高中" value="高中" label="高中"></el-option>
									<el-option key="中专" value="中专" label="中专"></el-option>
									<el-option key="大专" value="大专" label="大专"></el-option>
									<el-option key="本科" value="本科" label="本科"></el-option>
									<el-option key="研究生" value="研究生" label="研究生"></el-option>
									<el-option key="硕士" value="硕士" label="硕士"></el-option>
									<el-option key="博士" value="博士" label="博士"></el-option>
									<el-option key="博士后" value="博士后" label="博士后"></el-option>
									<el-option key="博士研究生" value="博士研究生" label="博士研究生"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="MaritalStatus_FormItem" prop="MaritalStatus">
								<template #label>
									<WtmLabelTooltip label="婚姻状况" tooltip="婚姻状况" />
								</template>
								<el-select v-model="searchData.MaritalStatus" clearable>
									<el-option key="未婚" value="未婚" label="未婚"></el-option>
									<el-option key="已婚" value="已婚" label="已婚"></el-option>
									<el-option key="离异" value="离异" label="离异"></el-option>
									<el-option key="丧偶" value="丧偶" label="丧偶"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IdCardNo_FormItem" prop="IdCardNo">
								<template #label>
									<WtmLabelTooltip label="身份证号" tooltip="身份证号码" />
								</template>
								<el-input v-model="searchData.IdCardNo" clearable></el-input>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="IsVeteran_FormItem" prop="IsVeteran">
								<template #label>
									<WtmLabelTooltip label="是否退伍军人" tooltip="是否为退伍军人" />
								</template>
								<el-select v-model="searchData.IsVeteran" clearable>
									<el-option key="是" :value="true" label="是"></el-option>
									<el-option key="否" :value="false" label="否"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="PoliticalStatus_FormItem" prop="PoliticalStatus">
								<template #label>
									<WtmLabelTooltip label="政治面貌" tooltip="政治面貌" />
								</template>
								<el-select v-model="searchData.PoliticalStatus" clearable>
									<el-option key="中共党员" value="中共党员" label="中共党员"></el-option>
									<el-option key="共青团员" value="共青团员" label="共青团员"></el-option>
									<el-option key="群众" value="群众" label="群众"></el-option>
									<el-option key="无党派人士" value="无党派人士" label="无党派人士"></el-option>
									<el-option key="其他" value="其他" label="其他"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="WorkYearsRange_FormItem" prop="WorkYearsRange">
								<template #label>
									<WtmLabelTooltip label="工龄范围" tooltip="工龄范围" />
								</template>
								<div class="range-input-container">
									<el-input-number
										v-model="searchData.WorkYearsStart"
										:min="0"
										:max="50"
										:precision="1"
										:controls="false"
										placeholder="起始"
										clearable
										controls-position="right"
										class="range-input-start"
									></el-input-number>
									<span class="range-separator">至</span>
									<el-input-number
										v-model="searchData.WorkYearsEnd"
										:min="0"
										:max="50"
										:precision="1"
										:controls="false"
										placeholder="结束"
										clearable
										controls-position="right"
										class="range-input-end"
									></el-input-number>
								</div>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" class="mb15">
							<el-form-item ref="CompanyYearsRange_FormItem" prop="CompanyYearsRange">
								<template #label>
									<WtmLabelTooltip label="司龄范围" tooltip="司龄范围" />
								</template>
								<div class="range-input-container">
									<el-input-number
										v-model="searchData.CompanyYearsStart"
										:min="0"
										:max="50"
										:precision="1"
										:controls="false"
										placeholder="起始"
										clearable
										controls-position="right"
										class="range-input-start"
									></el-input-number>
									<span class="range-separator">至</span>
									<el-input-number
										v-model="searchData.CompanyYearsEnd"
										:min="0"
										:max="50"
										:precision="1"
										:controls="false"
										placeholder="结束"
										clearable
										controls-position="right"
										class="range-input-end"
									></el-input-number>
								</div>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</template>
		</WtmSearcher>

		<div v-if="toolbar">
			<WtmButton
				v-auth="'/api/SysPerson/Add'"
				icon="fa fa-plus"
				type="primary"
				:button-text="$t('message._system.common.vm.add')"
				@click="OnCreateClick()"
			/>
			<WtmButton
				v-auth="'/api/SysPerson/BatchDelete'"
				icon="fa fa-trash"
				type="danger"
				:button-text="$t('message._system.common.vm.batchdelete')"
				:disabled="!hasSelectedRows"
				:confirm="$t('message._system.common.vm.deletetip')"
				@click="onBatchDelete()"
			/>
			<WtmButton
				v-auth="'/api/SysPerson/Batchassignjobs'"
				icon="fa fa-briefcase"
				type="success"
				button-text="批量分岗"
				:disabled="!hasSelectedRows"
				@click="onBatchJobAssignment()"
			/>
			<WtmButton
				v-auth="'/api/SysPerson/Import'"
				icon="fa fa-tasks"
				type="primary"
				:button-text="$t('message._system.common.vm.import')"
				@click="OnImportClick()"
			/>
			<WtmButton
				v-auth="'/api/sysperson/createaccounts'"
				icon="fa fa-cogs"
				type="success"
				:button-text="$t('message._system.common.vm.batchgenerate')"
				:disabled="!hasSelectedRows"
				@click="onBatchGenerate()"
			/>
			<WtmButton
				v-auth="'/api/sysperson/gensuppbyids'"
				icon="fa fa-plus-square"
				type="warning"
				button-text="批量生成补录"
				:disabled="!hasSelectedRows"
				@click="onGenSuppByIds()"
			/>
			<WtmButton
				v-auth="'/api/sysperson/gensuppbysearch'"
				icon="fa fa-plus-circle"
				type="info"
				button-text="按条件生成补录"
				:disabled="!hasSearchConditions"
				@click="onGenSuppBySearch()"
			/>
			<WtmButton
				v-auth="'/api/SysPerson/ExportExcel'"
				icon="fa fa-arrow-circle-down"
				type="primary"
				:button-text="$t('message._system.common.vm.export')"
				@click="onExport()"
			/>
		</div>
		<div class="main-content-layout">
			<div class="left-panel">
				<WtmDeptTree
					ref="deptTreeRef"
					title="筛选部门"
					@node-click="handleDeptNodeClick"
					@company-change="handleCompanyChange"
					:showCompanySelector="false"
					:showCompany="true"
					:auth="false"
				/>
			</div>

			<!-- 右侧表格 -->
			<div class="right-panel">
				<WtmTable ref="tableRef" v-bind="tableData" class="table-operation-area">
					<template #operation>
						<el-table-column :label="$t('message._system.common.vm.operate')" min-width="280" align="center" class-name="operation-column">
							<template v-slot="scope">
								<div class="operation-container">
									<WtmButton
										v-auth="'/api/SysPerson/Edit'"
										:is-text="true"
										icon="fa fa-pencil-square"
										type="warning"
										:button-text="$t('message._system.common.vm.edit')"
										@click="OnEditRowClick(scope.row)"
									/>
									<WtmButton
										v-if="scope.row.CanApprove == 'true'"
										:is-text="true"
										icon="-o"
										type="warning"
										button-text="审批"
										@click="OnDetailsRowClick(scope.row)"
									/>
									<WtmButton
										v-else
										v-auth="'/api/SysPerson/{id}'"
										:is-text="true"
										icon="fa fa-info-circle"
										type="info"
										:button-text="$t('message._system.common.vm.detail')"
										@click="OnDetailsRowClick(scope.row)"
									/>
									<WtmButton
										v-auth="'/api/sysperson/createaccounts'"
										:is-text="true"
										icon="fa fa-cogs"
										type="primary"
										:button-text="$t('message._system.common.vm.generate')"
										@click="onGenerate(scope.row)"
									/>
									<WtmButton
										v-auth="'/api/sysperson/gensuppbyids'"
										:is-text="true"
										icon="fa fa-plus-square"
										type="warning"
										button-text="生成补录"
										@click="onGenSuppRow(scope.row)"
									/>
									<WtmButton
										v-auth="'/api/SysPerson/BatchDelete'"
										icon="fa fa-trash"
										type="danger"
										:button-text="$t('message._system.common.vm.delete')"
										:confirm="$t('message._system.common.vm.deletetip')"
										:is-text="true"
										@click="onDelete(scope.row)"
									/>
								</div>
							</template>
						</el-table-column>
					</template>
				</WtmTable>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts" name="员工档案;true;HengTong.Areas.Person.Controllers;SysPerson">
import ElMessage from 'element-plus/es/components/message/index';
import { reactive, ref, getCurrentInstance, onMounted, computed, type ComponentInternalInstance, defineAsyncComponent } from 'vue';
import { SysPersonApi as api } from '/@/views/person/sysperson/api';
import other from '/@/utils/other';
import { ISysPersonView, ISysPersonQuery } from '/@/views/person/sysperson/api/interface';
import CreateDialog from './create.vue';
import EditDialog from './edit.vue';
import commonFunction from '/@/utils/commonFunction';
// import DetailsDialog from './details.vue';
import ImportDialog from './import.vue';
import { batchOperationsApi } from '/@/api/batchOperations';
// 打开分岗申请详情弹窗
const JobAssignmentDetailsDialog = defineAsyncComponent(() => import('/@/views/hr/syshrjobassignmentrequestbill/details.vue'));

const DetailsDialog = defineAsyncComponent(() => import('./details.vue'));
const { dateFormatYMD } = commonFunction();
// 常量定义
const API_ENDPOINTS = {
	ORGS: '/api/common/getorganizations',
	GROUPS: '/api/common/getgroups',
	JOB_POSITIONS: '/api/common/getjobpositions',
} as const;

const TABLE_HEADERS = [
	{ title: '排序', key: 'Order', type: 'text', isCheck: true },
	{ title: '姓名', key: 'Name', type: 'text', isCheck: true },
	{ title: '工号', key: 'StaffNo', type: 'text', isCheck: true },
	{
		title: '出生日期',
		key: 'BirthDate',
		type: 'text',
		isCheck: true,
		formatter: (row: ISysPersonView, value: any) => dateFormatYMD(row as any, 0 as any, value),
	},
	{ title: '年龄', key: 'Age', type: 'text', isCheck: true },
	{ title: '性别', key: 'Gender', type: 'text', isCheck: true },
	{ title: '民族', key: 'Ethnicity', type: 'text', isCheck: true },
	{ title: '学历', key: 'HighestEducation', type: 'text', isCheck: true },
	{ title: '婚否', key: 'MaritalStatus', type: 'text', isCheck: true },
	{ title: '退伍', key: 'IsVeteran', type: 'text', isCheck: true },
	{ title: '照片', key: 'PhotoId', type: 'image', isCheck: true },
	{ title: '身份证号', key: 'IdCardNo', type: 'text', isCheck: true },
	{ title: '身份证人像面', key: 'IdCardFrontPhotoId', type: 'image', isCheck: true },
	{ title: '身份证国徽面', key: 'IdCardBackPhotoId', type: 'image', isCheck: true },
	{ title: '身份证有效期', key: 'IdCardExpiryDate', type: 'text', isCheck: true },
	{ title: '户籍地', key: 'HouseholdRegistration', type: 'text', isCheck: true },
	{ title: '籍贯', key: 'NativePlace', type: 'text', isCheck: true },
	{ title: '政治', key: 'PoliticalStatus', type: 'text', isCheck: true },
	{ title: '工龄', key: 'WorkYears', type: 'text', isCheck: true },
	{ title: '司龄', key: 'CompanyYears', type: 'text', isCheck: true },
	{ title: '入党', key: 'PartyJoinDate', type: 'text', isCheck: true },
	{ title: '支部', key: 'PartyBranch', type: 'text', isCheck: true },
	{ title: '档案所在地', key: 'ArchiveLocation', type: 'text', isCheck: true },
	{ title: '存档号', key: 'ArchiveNo', type: 'text', isCheck: true },
	{ title: '档案年龄', key: 'ArchiveAgeDate', type: 'text', isCheck: true },
	{ title: '档案调出', key: 'ArchiveTransferOutDate', type: 'text', isCheck: true },
	{ title: '档案调入', key: 'ArchiveTransferInDate', type: 'text', isCheck: true },
	{ title: '参加工作', key: 'JoinWorkDate', type: 'text', isCheck: true },
	{ title: '家庭住址', key: 'HomeAddress', type: 'text', isCheck: true },
	{ title: '手机号', key: 'Phone', type: 'text', isCheck: true },
	{ title: '邮箱', key: 'Email', type: 'text', isCheck: true },
	{ title: '工资卡', key: 'SalaryBank', type: 'text', isCheck: true },
	{ title: '工资卡号', key: 'SalaryAccount', type: 'text', isCheck: true },
	{ title: '奖金卡', key: 'BonusBank', type: 'text', isCheck: true },
	{ title: '奖金卡号', key: 'BonusAccount', type: 'text', isCheck: true },
	{ title: '公司', key: 'OrgName', type: 'text', isCheck: true },
	{ title: '部门', key: 'GroupName', type: 'text', isCheck: true },
	{ title: '岗位', key: 'JobPositionName', type: 'text', isCheck: true },
	{ title: '简历', key: 'ResumeId', type: 'text', isCheck: true },
	{ title: '入职日期', key: 'HireDate', type: 'text', isCheck: true },
	{ title: '转正日期', key: 'ConfirmationDate', type: 'text', isCheck: true },
	{ title: '用工形式', key: 'EmploymentType', type: 'text', isCheck: true },
	{ title: '合同类型', key: 'ContractType', type: 'text', isCheck: true },
	{ title: '合同编号', key: 'ContractNo', type: 'text', isCheck: true },
	{ title: '合同起始日', key: 'ContractStartDate', type: 'text', isCheck: true },
	{ title: '合同终止日', key: 'ContractEndDate', type: 'text', isCheck: true },
	{ title: '离职日期', key: 'ResignationDate', type: 'text', isCheck: true },
	{ title: '离职原因', key: 'ResignationReason', type: 'text', isCheck: true },
	{ title: '离职类型', key: 'ResignationType', type: 'text', isCheck: true },
	{
		title: '状态',
		key: 'State',
		type: 'tag',
		isCheck: true,
		tagType: (row: ISysPersonView) => {
			const statusMap: Record<string, string> = {
				在职: 'success',
				试用期: 'info',
				离职: 'danger',
				退休: 'warning',
			};
			return statusMap[row.State || ''] || 'default';
		},
	},
	{ title: '血型', key: 'BloodType', type: 'text', isCheck: true },
	{ title: '爱好特长', key: 'Hobbies', type: 'text', isCheck: true },
] as const;

const ci = getCurrentInstance() as ComponentInternalInstance;
const loading = ref(false);

const props = withDefaults(
	defineProps<{
		/** 是否显示搜索(筛选)栏 */
		searchBar?: boolean;
		/** 是否显示工具栏 */
		toolbar?: boolean;
		/** 是否禁用表格任何操作 */
		isDisabled?: boolean;
		/** 默认筛选 */
		filters?: ISysPersonQuery;
		/** 主表ID */
		entityId?: string | null;
	}>(),
	{
		searchBar: true,
		toolbar: true,
		isDisabled: true,
		filters: () => ({}),
		entityId: null,
	}
);

const stateData = reactive({
	AllSysOrgs: [] as any[],
	AllSysGroups: [] as any[],
	AllSysJobPositions: [] as any[],
});

const searchData = ref<ISysPersonQuery>({
	State: '在职',
});

const tableRef = ref();

// 初始化表格数据
const tableData = ref({
	data: [],
	header: TABLE_HEADERS,
	config: {
		total: 0,
		loading: true,
		isSerialNo: true,
		isSelection: true,
		isOperate: props.isDisabled,
	},
});

// 计算属性 - 判断是否有选中行
const hasSelectedRows = computed(() => {
	const selectedRows = tableRef.value?.getSelectedRows() || [];
	return selectedRows.length > 0;
});

// 添加计算属性判断是否有搜索条件
const hasSearchConditions = computed(() => {
	const data = searchData.value;
	if (!data) return false;

	// 检查所有搜索字段是否有值
	return Object.values(data).some((value) => {
		if (value === null || value === undefined || value === '') {
			return false;
		}
		// 如果是数组，检查长度
		if (Array.isArray(value)) {
			return value.length > 0;
		}
		return true;
	});
});

// 统一的错误处理函数
const handleError = (error: any) => {
	other.setFormError(ci, error);
	loading.value = false;
};

// 初始化表格数据
const getTableData = async () => {
	try {
		await tableRef.value.doSearch(api().search, searchData.value);
	} catch (error) {
		handleError(error);
	}
};

// 对话框操作
const OnCreateClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.add') || '新增', CreateDialog, null, getTableData);
};

const OnEditRowClick = (row: ISysPersonView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.edit') || '编辑', EditDialog, row, getTableData);
};

const OnDetailsRowClick = (row: ISysPersonView) => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.detail') || '详情', DetailsDialog, row, getTableData);
};

const OnImportClick = () => {
	other.openDialog(ci.proxy?.$t('message._system.common.vm.import') || '导入', ImportDialog, null, getTableData);
};

// 删除操作
const onDelete = async (row: ISysPersonView) => {
	try {
		const ids = [row.ID] as (string | number)[];
		await api().delete(ids);
		getTableData();
	} catch (error) {
		handleError(error);
	}
};

// 批量删除
const onBatchDelete = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPersonView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		try {
			await api().delete(selectedIds);
			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			handleError(error);
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要删除的数据');
	}
};

// 导出操作
const onExport = () => {
	const selected = tableRef.value?.getSelectedRows();
	if (selected && selected.length > 0) {
		api().exportById(selected.map((x: any) => x.ID));
	} else {
		api().export({});
	}
};

// 生成账户
const onGenerate = async (row: ISysPersonView) => {
	try {
		const ids = [row.ID] as (string | number)[];
		const response = await api().createAccounts(ids);

		if (response.Code === 200) {
			ElMessage.success(String(response.Message) || '操作成功');
		} else {
			ElMessage.error(String(response.Message) || '操作失败');
		}
		getTableData();
	} catch (error) {
		handleError(error);
	}
};

// 批量生成账户
const onBatchGenerate = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPersonView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		try {
			const response = await api().createAccounts(selectedIds);

			if (response.Code === 200) {
				ElMessage.success(String(response.Message) || '操作成功');
			} else {
				ElMessage.error(String(response.Message) || '操作失败');
			}

			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			handleError(error);
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要操作的数据');
	}
};

// 生成补录数据相关操作
const onGenSuppByIds = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();
	const selectedIds = selectedRows?.map((x: ISysPersonView) => x.ID) as (string | number)[];

	if (selectedIds && selectedIds.length > 0) {
		loading.value = true;
		try {
			const response = await api().genSuppByIds(selectedIds);

			if (response.Code === 200) {
				ElMessage.success(String(response.Message) || '批量生成补录数据成功');
			} else {
				ElMessage.error(String(response.Message) || '批量生成补录数据失败');
			}

			tableRef.value?.clearSelection();
			getTableData();
		} catch (error) {
			ElMessage.error('批量生成补录数据失败');
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请选择要操作的数据');
	}
};

const onGenSuppBySearch = async () => {
	loading.value = true;
	try {
		const response = await api().genSuppBySearch(searchData.value);

		if (response.Code === 200) {
			ElMessage.success(String(response.Message) || '按条件生成补录数据成功');
		} else {
			ElMessage.error(String(response.Message) || '按条件生成补录数据失败');
		}

		getTableData();
	} catch (error) {
		ElMessage.error('按条件生成补录数据失败');
	} finally {
		loading.value = false;
	}
};

const onGenSuppRow = async (row: ISysPersonView) => {
	loading.value = true;
	try {
		const ids = [row.ID] as (string | number)[];
		const response = await api().genSuppByIds(ids);

		if (response.Code === 200) {
			ElMessage.success(String(response.Message) || '生成补录数据成功');
		} else {
			ElMessage.error(String(response.Message) || '生成补录数据失败');
		}
		getTableData();
		loading.value = false;
	} catch (error) {
		ElMessage.error('生成补录数据失败');
	} finally {
		loading.value = false;
	}
};

// 批量分岗操作
const onBatchJobAssignment = async () => {
	const selectedRows = tableRef.value?.getSelectedRows();

	if (selectedRows && selectedRows.length > 0) {
		// 提取有效的ID
		const validIds = selectedRows
			.map((x: any) => x.ID)
			.filter((id: string | number | null | undefined): id is string | number => id !== null && id !== undefined);

		loading.value = true;
		try {
			const response = await batchOperationsApi().batchJobAssignment(validIds);

			// 根据返回的状态码判断操作是否成功
			if (response.Code == 200) {
				// 先清除选择状态
				tableRef.value?.clearSelection();
				// 再重新获取数据
				getTableData();
				ElMessage.success('批量分岗单据生成成功');
				other.openDialog('分岗申请', JobAssignmentDetailsDialog, { ID: response.Data }, getTableData);
			} else {
				// 显示后端返回的错误信息
				ElMessage.error(response.Message || '操作失败');
			}
		} catch (error: any) {
			// 如果是网络错误或其他异常，显示通用错误信息
			if (error.response?.Data?.Message) {
				ElMessage.error(error.response.Data.Message);
			} else {
				ElMessage.error('操作失败，请稍后重试');
			}
		} finally {
			loading.value = false;
		}
	} else {
		ElMessage.error(ci.proxy?.$t('message._system.common.vm.check') || '请先选择数据');
	}
};

// 处理公司选择变化
const handleCompanyChange = (companyId: string | number, company: any) => {
	// 清空部门筛选
	searchData.value.GroupId = '';

	// 设置公司ID进行查询
	if (companyId) {
		searchData.value.OrgId = String(companyId);
	} else {
		// 如果清空公司选择，则清空公司ID
		searchData.value.OrgId = '';
	}

	// 直接根据公司ID查询数据
	getTableData();
};

// 处理部门树节点点击
const handleDeptNodeClick = (node: any) => {
	// 如果点击的是根节点或者Value为空，则清空部门筛选
	if (!node.Value || node.Value === 'all') {
		searchData.value.GroupId = '';
		searchData.value.OrgId = '';
	} else {
		searchData.value.GroupId = node.Value;
		// 如果Tag参数不为空，则赋值给OrgId来查询特定公司下的部门数据
		if (node.Tag) {
			searchData.value.OrgId = node.Tag;
		} else {
			searchData.value.OrgId = node.Value;
			searchData.value.GroupId = '';
		}
	}
	getTableData();
};

// 加载选择列表数据
const loadSelectListData = async () => {
	try {
		const [orgs, groups, jobPositions] = await Promise.allSettled([
			other.getSelectList(API_ENDPOINTS.ORGS, [], false),
			other.getSelectList(API_ENDPOINTS.GROUPS, [], false),
			other.getSelectList(API_ENDPOINTS.JOB_POSITIONS, [], false),
		]);

		// 处理选择列表结果，即使部分失败也继续
		if (orgs.status === 'fulfilled') stateData.AllSysOrgs = orgs.value;
		if (groups.status === 'fulfilled') stateData.AllSysGroups = groups.value;
		if (jobPositions.status === 'fulfilled') stateData.AllSysJobPositions = jobPositions.value;
	} catch (error) {
		// 静默处理错误，不影响主流程
	}
};

// 页面加载时
onMounted(async () => {
	loading.value = true;

	try {
		// 并行加载选择列表数据和表格数据
		await Promise.all([loadSelectListData(), getTableData()]);
	} catch (error) {
		handleError(error);
	} finally {
		loading.value = false;
	}
});
</script>

<style lang="scss" scoped>
.range-input-container {
	display: flex;
	align-items: center;
	gap: 12px;
	width: 100%;

	.range-input-start,
	.range-input-end {
		flex: 1;
		min-width: 0;

		:deep(.el-input-number) {
			width: 100%;
		}

		:deep(.el-input__wrapper) {
			border-radius: 6px;
			box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;

			&:hover {
				box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
			}

			&.is-focus {
				box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
			}
		}

		:deep(.el-input__inner) {
			font-size: 14px;
			color: var(--el-text-color-primary);
		}

		:deep(.el-input-number__decrease),
		:deep(.el-input-number__increase) {
			border: none;
			background: var(--el-fill-color-light);
			color: var(--el-text-color-regular);
			transition: all 0.2s ease;

			&:hover {
				background: var(--el-color-primary-light-9);
				color: var(--el-color-primary);
			}
		}
	}

	.range-separator {
		font-size: 14px;
		color: var(--el-text-color-regular);
		font-weight: 500;
		padding: 0 4px;
		user-select: none;
		white-space: nowrap;
	}
}

// 响应式优化
@media (max-width: 768px) {
	.range-input-container {
		flex-direction: column;
		gap: 8px;

		.range-input-start,
		.range-input-end {
			width: 100%;
		}

		.range-separator {
			transform: rotate(90deg);
			margin: 4px 0;
		}
	}
}
</style>
